package com.ptu.server.Impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.RandomUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.ptu.dto.UserDTO;
import com.ptu.dto.UserLoginDTO;
import com.ptu.entity.User;
import com.ptu.mapper.UserMapper;
import com.ptu.server.UserServer;
import com.ptu.util.*;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;


@Service
@Slf4j
public class UserServerImpl implements UserServer {

    @Autowired
    private UserMapper userMapper;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public void register(UserDTO userDTO) {
        userMapper.register(userDTO);
    }

    @Override
    public Result sendCode(String phone, HttpSession session) {
        // 1. 校验手机号
        if (RegexUtils.isPhoneInvalid(phone)) {
            return Result.error("手机号格式错误");
        }
        //数据库中查询手机号是否存在，不存在返回该用户不存在，需要注册
        if (!userMapper.isPhoneExist(phone)) {
            return Result.error("该用户不存在，请先注册");
        }
        // 2. 生成验证码
        String code = RandomUtil.randomNumbers(6);
        // 3. 保存验证码到redis
        stringRedisTemplate.opsForValue().set("login:code:" + phone, code, 5, TimeUnit.MINUTES);
        //log.info("发送验证码成功：验证码：{}", code);
        System.out.println("发送验证码成功：验证码：" + code);

        // 直接返回验证码给前端
        Map<String, String> data = new HashMap<>();
        data.put("code", code);
        return Result.success(data);
    }

    @Override
    public Result login(UserLoginDTO loginForm, HttpSession session) {
        // 1. 校验图形验证码
        String sessionCaptcha = (String) session.getAttribute("captcha");
        String inputCaptcha = loginForm.getCaptcha();

        if (sessionCaptcha == null || !sessionCaptcha.equalsIgnoreCase(inputCaptcha)) {
            return Result.error("图形验证码错误");
        }
        System.out.println("图形验证码验证成功");

        // 2. 校验手机号
        String phone = loginForm.getPhone();
        if (RegexUtils.isPhoneInvalid(phone)) {
            return Result.error("手机号格式错误");
        }

        // 3. 从 Redis 获取验证码并验证
        String cacheCode = stringRedisTemplate.opsForValue().get("login:code:" + phone);
        String code = loginForm.getCode();
        if (cacheCode == null || !cacheCode.equals(code)) {
            return Result.error("验证码错误");
        }

        // 4. 根据手机号查询用户
        User user = userMapper.getUserByPhone(phone);
        if (user == null) {
            return Result.error("该用户不存在，请先注册");
        }

        // 5. 生成JWT token
        UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
        String token = jwtUtil.generateToken(userDTO);
        System.out.println("生成JWT token" + token);

        // 6. 返回token
        return Result.success(token);
    }

    @Override
    public void update(UserDTO userDTO) {
        System.out.println("修改用户信息" + userDTO);
        userMapper.update(userDTO);
    }

    @Override
    public void saveAvatar(Integer id, String img) {
        System.out.println("保存用户头像" + id + " " + img);
        userMapper.updateById(id, img);
    }

    @Override
    public UserDTO getUser() {
        UserDTO user = UserHolder.getUser();
        Integer id = user.getId();
        System.out.println("获取用户信息" + id);
        return userMapper.getUser(id);
    }

    @Override
    public PageResult getUserList(String phone, String userName,Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);

        Page<User> page = userMapper.pageQuery(phone, userName);
        return new PageResult(page.getTotal(), page.getResult());

    }

    @Override
    public User adminGetUser(Integer id) {
        User user = userMapper.adminGetUser(id);
        return user;
    }

    @Override
    public void adminUpdate(UserDTO userDTO) {
        System.out.println("修改用户信息" + userDTO);

        User user = new User();

        BeanUtil.copyProperties(userDTO, user);

        userMapper.adminUpdate(user);
    }

    @Override
    public void delete(Integer id) {
        userMapper.delete(id);
    }

    @Override
    public void adminAdd(UserDTO user) {
        userMapper.adminAdd(user);
    }


    @Override
    public Result adminLogin(String adminName, String password) {
        //通过用户名查询用户
        User user = userMapper.adminLogin(adminName, password);
        if (user == null) {
            return Result.error("用户名或密码错误");
        }
        if (user.getGender() != 0) {
            return Result.error("该用户不是管理员，请重新登录");
        }

        // 4. 生成JWT token
        UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
        String token = jwtUtil.generateToken(userDTO);
        System.out.println("生成JWT token" + token);

        // 5. 返回token
        return Result.success(token);
    }


}
